from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import sys

import os
from google.appengine.ext.webapp import template

from models import *


class MainPage(webapp.RequestHandler):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='user':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/admin")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
        	user = users.get_current_user()
		t_email=user.email()
		usrdtl=db.GqlQuery("SELECT * FROM userDetails")
		for k in usrdtl:
			if k.email==t_email:
				user_id=k.userid
		teamDetails=db.GqlQuery("SELECT * FROM teamDetails")
		projectDetails=db.GqlQuery("SELECT * FROM projectDetails")
		notif=db.GqlQuery("SELECT * FROM notificationDetails")
		tid=[]
		temp=[]
		fla=0
		for i in teamDetails:
			stri=i.teammember
			b=stri.split(',')
			for j in b:
				if j==user_id:
					fla=1
					tid.append(i.projectids)
		t=[]
		for i in notif :
			if i.userid==user_id:	
				temp1=[i.notification,i.notificationid]
				t.append(temp1)
				
			
		for i in projectDetails:
			for j in tid:
				if i.projectid==j:
					temp=[i.projectname,i.projectid,i.teamid,i.category,i.abstract,i.confirmed]
			tid.append(temp)
		path = os.path.join(os.path.dirname(__file__),'tab.html')#use template
		self.response.out.write(template.render(path,{"items":tid,"noti":t}))#using template
	def post(self):
		delid=self.request.get("delval")
		notif=db.GqlQuery("SELECT * FROM notificationDetails WHERE notificationid='%s'"%(delid))
		for i in notif :
			i.delete()
		self.redirect("/")

application=webapp.WSGIApplication([('/',MainPage)],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
